package com.atguigu.gulimall.order.web;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberResponseVo;
import com.atguigu.gulimall.order.Feign.MemberFeignService;
import com.atguigu.gulimall.order.constant.OrderConstant;
import com.atguigu.gulimall.order.interceptor.Myinterceptor;
import com.atguigu.gulimall.order.service.OrderService;
import com.atguigu.gulimall.order.to.OrderTo;
import com.atguigu.gulimall.order.vo.CreateOrderVo;
import com.atguigu.gulimall.order.vo.MemberAddressVo;
import com.atguigu.gulimall.order.vo.OrderConfirmVo;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.Thymeleaf;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.UUID;
import java.util.concurrent.ExecutionException;

@Controller
public class OrderWebController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private MemberFeignService memberFeignService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private AmqpTemplate amqpTemplate;


    @GetMapping("/toTrade")
    public String toTrade(Model model, HttpServletRequest request) throws ExecutionException, InterruptedException {
        OrderConfirmVo orderConfirmVo = orderService.confirmOrder();
        String token = UUID.randomUUID().toString().replace("-", "");
        request.getSession().setAttribute("token", token);
        ThreadLocal<MemberResponseVo> loginUser = Myinterceptor.loginUser;
        redisTemplate.opsForValue().set(OrderConstant.ORDER_TOKEN+loginUser.get().getId(), token);
        orderConfirmVo.setOrderToken(token);
        model.addAttribute("confirmInfo", orderConfirmVo);
        return "confirm";
    }

    @ResponseBody
    @GetMapping("/getCharge")
    public BigDecimal getCharge(@RequestParam("id") Long id) {
       BigDecimal charge = orderService.getcharge(id);
        return charge;
    }

    /**
     * 提交订单
     */
    @PostMapping("/createOrder")
    public String createOrder(CreateOrderVo createOrderVo, Model model, HttpServletRequest request) {
        OrderTo orderTo = orderService.createOrder(createOrderVo);
        if(orderTo.getCode()==0){
            //创建订单成功
            model.addAttribute("order",orderTo);
            //发送消息给延时队列, 查看用户是否超时未支付
            amqpTemplate.convertAndSend("");
            return "pay";
        }else{
            //创建订单失败
            return "redirect:http://order.gulimall.com/toTrade";
        }
    }
}
